﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.Domain.Tree;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.Infra;
using B.S.Packaged.WebAPI.Write.Applications.Commands.Workshop;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers
{
    public class AddWorkshopHander : IRequestHandler<AddWorkshopCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;
        private readonly IDapperContext dapper;

        public AddWorkshopHander(IMapper mapper, ISqlSugarClient db, IDapperContext dapper)
        {
            this.mapper = mapper;
            this.db = db;
            this.dapper = dapper;
        }

        /// <summary>
        /// 添加车间操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(AddWorkshopCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var entity = mapper.Map<Domain.Tree.Workshop>(request);
            var two = $"SELECT * from Workshop where WorkshopName='{request.WorkshopName}'";
            var one = await dapper.QueryAsync<Domain.Tree.Workshop>(two);

            ///判断查询的长度
            if (one.Count() > 0)
            {
                result.code = APIResultCode.noname;
                result.msg = APIResultCode.noname.ToString();
                result.data = 0;
                return await Task.FromResult(result);
            }
            var sql = $"INSERT INTO Workshop (WorkshopName) values('{request.WorkshopName}')";
            var list = await dapper.ExecuteAsync(sql);

            if (list > 0)
            {
                result.code = APIResultCode.success;
                result.msg = APIResultCode.success.ToString();
                result.data = list;
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = APIResultCode.failed.ToString();
                result.data = list;
            }

            return await Task.FromResult(result);
        }
    }
}
